package com.bbs.web;

import com.alibaba.fastjson.JSONObject;
import com.bbs.common.consts.CommonConstant;
import com.bbs.common.dto.LoginDTO;
import com.bbs.common.vo.DataResult;
import com.bbs.common.vo.LoginVo;
import com.bbs.dto.RegisterDTO;
import com.bbs.service.LoginService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@RestController
@Log4j2
public class LoginController {

    @Autowired
    private LoginService loginService;

//    @PostMapping("login")
//    public DataResult login(@Valid @RequestBody LoginDTO loginDTO, HttpSession session) {
//        LoginVo login = loginService.login(loginDTO);
//        session.setAttribute(CommonConstant.SESSION_USER, JSONObject.toJSONString(login));
//        return DataResult.success();
//    }
//
//    @PostMapping("register")
//    public DataResult register(@Valid @RequestBody RegisterDTO registerDTO) {
//        loginService.register(registerDTO);
//        return DataResult.success();
//    }
    @PostMapping("login")
    public DataResult login(@Valid @RequestBody LoginDTO loginDTO, HttpSession session) {
        LoginVo login = loginService.login(loginDTO);
        session.setAttribute(CommonConstant.SESSION_USER, JSONObject.toJSONString(login));
        log.info("User logged in: {}", login); // 查看是否添加入session
        return DataResult.success(login);
    }

    @PostMapping("register")
    public DataResult register(@Valid @RequestBody RegisterDTO registerDTO) {
        loginService.register(registerDTO);
        return DataResult.success();
    }
}
